<template>
  <div class="table-box">
    <ProTable ref="proTable" :columns="columns" :request-api="getTableList" :data-callback="dataCallback">
      <!-- 表格 header 按钮 -->
      <template #tableHeader>
        <el-button v-auth="'add'" type="primary" :icon="CirclePlus" @click="openDrawer('新增')">新增商品</el-button>
        <el-button v-auth="'batchAdd'" type="primary" :icon="Upload" plain @click="batchAdd">批量添加商品</el-button>
        <el-button v-auth="'export'" type="primary" :icon="Download" plain @click="downloadFile">导出商品数据</el-button>
      </template>
      <!-- 菜单操作 -->
      <template #operation="scope">
        <el-button type="primary" link :icon="EditPen" @click="openDrawer('编辑', scope.row)">编辑</el-button>
        <el-button type="primary" link :icon="Delete" @click="deleteGoods(scope.row)"> 删除</el-button>
      </template>
    </ProTable>
    <el-image-viewer v-if="imgViewVisible" :url-list="[imageUrl]" @close="imgViewVisible = false" />
    <GoodsDrawer ref="drawerRef" />
    <ImportExcel ref="dialogRef" />
  </div>
</template>

<script setup lang="tsx" name="goodsMange">
import { ref } from "vue";
import { ColumnProps, ProTableInstance } from "@/components/ProTable/interface";
import { Delete, EditPen, CirclePlus, Download, Upload, CopyDocument } from "@element-plus/icons-vue";
import ProTable from "@/components/ProTable/index.vue";
import { useHandleData } from "@/hooks/useHandleData";
import { Goods } from "@/api/interface";
import GoodsDrawer from "@/views/proTable/components/GoodsDrawer.vue";
import {
  addGoods,
  BatchAddGoods,
  deleteGoodsAPI,
  editGoods,
  exportGoods,
  getGoodsConditions,
  getGoodsList
} from "@/api/modules/goods";
import { getCategorySubList } from "@/api/modules/category";
import { ElMessageBox } from "element-plus";
import { useDownload } from "@/hooks/useDownload";
import ImportExcel from "@/components/ImportExcel/index.vue";

const proTable = ref<ProTableInstance>();

// 表格配置项
const columns: ColumnProps<Goods.ResGoods>[] = [
  {
    prop: "name",
    width: 120,
    label: "商品名称",
    search: { el: "input", tooltip: "我是搜索提示" },
    render: scope => {
      return (
        <div style="display: flex; justify-content: center; align-items: center; gap: 8px;">
          {/* 限制名称长度，超出部分显示省略号 */}
          <span style="max-width: 80px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">{scope.row.name}</span>
          <el-icon v-copy={scope.row.name} style="cursor: pointer;">
            <CopyDocument />
          </el-icon>
        </div>
      );
    }
  },
  {
    prop: "code",
    label: "商品编码",
    search: { el: "input", tooltip: "编码：G+21位数字" },
    width: 120,
    render: scope => {
      return (
        <div style="display: flex; justify-content: center; align-items: center; gap: 8px;">
          {/* 限制名称长度，超出部分显示省略号 */}
          <span style="max-width: 80px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">{scope.row.code}</span>
          <el-icon v-copy={scope.row.code} style="cursor: pointer;">
            <CopyDocument />
          </el-icon>
        </div>
      );
    }
  },
  { prop: "price", label: "商品价格" },
  {
    prop: "conditionName",
    label: "成色",
    enum: getGoodsConditions,
    search: { el: "select", props: { filterable: true } },
    fieldNames: { label: "name", value: "name" }
  },
  { prop: "stock", label: "商品库存" },
  {
    prop: "categoryName",
    label: "商品分类",
    enum: getCategorySubList,
    search: { el: "select", props: { filterable: true } },
    fieldNames: { label: "name", value: "name" }
  },
  {
    prop: "pictures",
    label: "商品图片",
    width: 450,
    render: scope => {
      return (
        <div>
          {scope.row.pictures.map((item, index) => (
            <img
              key={index}
              width="100px"
              style={{ margin: "5px" }}
              onClick={() => showLargeImage(item.url)}
              height="100px"
              src={item.url}
              alt={item.name}
            />
          ))}
        </div>
      );
    }
  },
  { prop: "createTime", label: "创建时间" },
  { prop: "updateTime", label: "更新时间" },
  { prop: "operation", label: "操作", width: 165, fixed: "right" }
];

const imgViewVisible = ref(false);
const imageUrl = ref("");
const showLargeImage = (url: string) => {
  imageUrl.value = url;
  imgViewVisible.value = true;
};

const dataCallback = (data: any) => {
  console.log(data);
  return {
    list: data.list,
    total: data.total,
    pageNum: data.pageNum,
    pageSize: data.pageSize
  };
};

const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  newParams.createTime && (newParams.startTime = newParams.createTime[0]);
  newParams.createTime && (newParams.endTime = newParams.createTime[1]);
  delete newParams.createTime;
  return getGoodsList(newParams);
};

const deleteGoods = async (params: Goods.ResGoods) => {
  await useHandleData(deleteGoodsAPI, { id: [params.id] }, `删除【${params.name}】商品`);
  proTable.value?.getTableList();
};

const downloadFile = async () => {
  ElMessageBox.confirm("确认导出商品数据?", "温馨提示", { type: "warning" }).then(res => {
    console.log(res);
    useDownload(exportGoods, "商品列表", proTable.value?.searchParam);
  });
};

const dialogRef = ref<InstanceType<typeof ImportExcel> | null>(null);
const batchAdd = () => {
  const params = {
    title: "商品",
    tempApi: exportGoods,
    importApi: BatchAddGoods,
    getTableList: proTable.value?.getTableList
  };
  dialogRef.value?.acceptParams(params);
};

// 打开 drawer(新增、查看、编辑)
const drawerRef = ref<InstanceType<typeof GoodsDrawer> | null>(null);
const openDrawer = (title: string, row: Partial<Goods.ResGoods> = {}) => {
  const params = {
    title,
    isView: title === "查看",
    row: { ...row },
    api: title === "新增" ? addGoods : title === "编辑" ? editGoods : undefined,
    getTableList: proTable.value?.getTableList
  };
  console.log(drawerRef);
  drawerRef.value?.acceptParams(params);
};
</script>
